<template>
  <div>
    <a-modal v-model:visible="modalVisible" title="添加链接" @ok="handleOk">
      <a-input v-model:value="inputValue" placeholder="请输入链接地址" />
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import setLinkUrl from '@/services/order/setLinkUrl'
const [, setLinkUrlFn] = setLinkUrl()

const props = defineProps<{
  visible: boolean
  orderId: Number
  value: String
}>()
const emit = defineEmits<{
  (e: 'update:visible', value: boolean): void
  (e: 'refresh'): void
}>()

const modalVisible = ref<Boolean>(props.visible)
const orderId = ref<Number>(props.orderId)
const inputValue = ref<String>(props.value)

watch(
  () => [props.visible, props.orderId, props.value],
  ([newVisible, orderIdValue, newValue]) => {
    modalVisible.value = newVisible
    orderId.value = orderIdValue
    inputValue.value = newValue
  },
  { immediate: true }
)
watch(modalVisible, (newVal) => {
  emit('update:visible', newVal)
})
const handleOk = (e: MouseEvent) => {
  if (!isValidUrl(inputValue.value)) {
    message.warning('请输入合法的网址（需以 http:// 或 https:// 开头）')
    return
  }
  modalVisible.value = false
  updateOrderLink()
}
const isValidUrl = (url: string): boolean => {
  const pattern = /^(https?:\/\/)[^\s/$.?#].[^\s]*$/i
  return pattern.test(url)
}

const updateOrderLink = async () => {
  const [err, res] = await setLinkUrlFn({
    orderId: orderId.value,
    linkUrl: inputValue.value
  })

  if (!err) {
    message.success('操作成功')
    emit('refresh')
  } else {
    message.error(err.message)
  }
}
</script>
